
import LocalValue from "../tools/LocalValue";
import EventDispatcher from "../event/EventDispatcher";
let LOCAL_MUSIC_FLAG: string = "LOCAL_MUSIC_FLAG";
let LOCAL_SOUND_VOLUME: string = "LOCAL_SOUND_VOLUME";
let LOCAL_MUSIC_VOLUME: string = "LOCAL_MUSIC_VOLUME";
export default class AudioManager extends EventDispatcher {

    static MUSIC_OPEN: string = 'music_open'
    static MUSIC_CLOSE: string = 'music_close';


    private soundVolume: LocalValue;
    private musicVolume: LocalValue;
    private musicFlag: LocalValue;

    private constructor() {
        super();
    }

    getSoundVolume() {
        if (!this.soundVolume) {
            return 0;
        }
        return this.soundVolume.getValue();
    }

    getMusicVolume() {
        if (!this.musicVolume) {
            return 0;
        }
        return this.musicVolume.getValue();
    }

    getMusicFlag() {
        if (!this.musicFlag) {
            return false;
        }
        let num = this.musicFlag.getValue();
        return num == 1 ? true : false;
    }


    private static ins: AudioManager;
    static instance() {
        if (!AudioManager.ins) {
            AudioManager.ins = new AudioManager();
        }
        return AudioManager.ins;
    }

    init(projectName: string) {
        this.soundVolume = new LocalValue(projectName + LOCAL_SOUND_VOLUME, 1);
        this.musicFlag = new LocalValue(projectName + LOCAL_MUSIC_FLAG, 1);
        this.musicVolume = new LocalValue(projectName + LOCAL_MUSIC_VOLUME, 1);
    }

    setMusicVolume(num: number) {
        if (!this.musicVolume) {
            return;
        }
        this.musicVolume.setValue(num);
    }

    setSoundVolume(num: number) {
        if (!this.soundVolume) {
            return;
        }
        this.soundVolume.setValue(num);
    }

    setMusicFlag(flag: boolean) {
        if (!this.musicFlag) {
            return;
        }
        let num = flag ? 1 : 0;
        this.musicFlag.setValue(num);
        if (num == 1) {
            this.publish(AudioManager.MUSIC_OPEN)
        } else {
            this.publish(AudioManager.MUSIC_CLOSE)
        }
    }
}
